﻿using IronLua.Metadata;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IronLua
{
    public class LuaEnvironment
    {
        internal const string EnvKey = "_ENV";
        internal const string GlobalsRegistryKey = "_G";

        static LuaEnvironment()
        {

        }

        private IDictionary<object, object> basicMetatables;
        private object globals;

        public LuaEnvironment()
        {
            this.globals = this.CreateGlobals();
            this.StdOut = Console.Out;
            this.StdErr = Console.Error;
            this.basicMetatables = Enum.GetValues(typeof(ValueType)).Cast<ValueType>().ToDictionary(vt => (object)vt, vt => (object)null);
        }

        public TextWriter   StdOut { get; set; }
        public TextWriter   StdErr { get; set; }
        public object       Globals { get { return this.globals; } set { this.globals = value; } }
        public IDictionary<object, object> BasicMetatables { get { return this.basicMetatables; } }
        public Lua CreateInterpreter()
        {
            var thread = new Thread(this, parent: null);
            return new Lua(this, thread);
        }

        private IDictionary<object, object> CreateGlobals()
        {
            var globalsTable = new Dictionary<object, object>()
            {
                { "print",  Builtin.Functions.print },
            };

            globalsTable[LuaEnvironment.GlobalsRegistryKey] = globalsTable;

            return globalsTable;
        }

    }
}
